package com.example.demo.security;

import com.example.demo.bean.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.List;

@Component("myUserDetailsService")
public class UserServiceImpl implements UserDetailsService {

    @Autowired
    private  UserService userService;

    @Override
    public  UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user=userService.login(username);
        if(null==user){
            throw new UsernameNotFoundException("用户名错误");
        }else if(user.getStatus() == 1){
            throw new UsernameNotFoundException("账号已锁定");
        }

        List<User> role=  userService.findUserByUserId(user);
        String type=role.get(0).getType();
        String []authorities=new String[1];
            authorities[0]="ROLE_"+type;
        System.out.println(authorities[0]);

        org.springframework.security.core.userdetails.User result=
                new org.springframework.security.core.userdetails.User(
                        username,user.getPassword(), AuthorityUtils.createAuthorityList(authorities[0])
                );
        return result;
    }
}
